
package com.intelligent.mts.da.codec;

import com.intelligent.mts.da.utils.JaxbUtil;
import com.intelligent.mts.da.xmlmessage.Validate;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.io.StringWriter;
import java.nio.charset.Charset;


public abstract class AbstractHttpXmlEncoder<T> extends
        MessageToMessageEncoder<T> {
    StringWriter writer = null;
    final static String CHARSET_NAME = "UTF-8";
    final static Charset UTF_8 = Charset.forName(CHARSET_NAME);

    protected ByteBuf encode0(ChannelHandlerContext ctx, Object body)
	    throws Exception {

		String result = null;
		if (body instanceof String && "WSDL".equalsIgnoreCase((String) body)){
			result = (String) body;
		}else
		 result = JaxbUtil.convertToXml(body);
		ByteBuf encodeBuf = Unpooled.copiedBuffer(result, UTF_8);
		return encodeBuf;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
	    throws Exception {
	// 释放资源
	if (writer != null) {
	    writer.close();
	    writer = null;
	}
    }

}
